<?php

namespace App\Http\Controllers;

// use App\Models\WechatUser;
use App\Models\WechatServiceAccountUser as WechatUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class WechatUserController extends Controller
{
    /**
     * 构造函数，添加中间件验证
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('admin');
    }

    /**
     * 显示微信用户列表，支持搜索功能
     *
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        try {
            Log::info('开始查询微信用户列表', [
                'search' => $request->input('search')
            ]);

            $query = WechatUser::query();

            // 处理搜索条件
            if ($search = $request->input('search')) {
                $query->where(function($q) use ($search) {
                    // 尝试将搜索词转换为数字，用于ID查询
                    if (is_numeric($search)) {
                        $q->where('id', $search);
                    }
                    // 同时支持昵称模糊查询
                    $q->orWhere('nickname', 'like', "%{$search}%");
                });

                Log::info('应用搜索条件', [
                    'search_term' => $search
                ]);
            }

            // 获取分页数据
            $wechatUsers = $query->latest()
                               ->paginate(15)
                               ->withQueryString();

            Log::info('微信用户查询完成', [
                'total_results' => $wechatUsers->total(),
                'current_page' => $wechatUsers->currentPage()
            ]);

            return view('wechat.users.index', compact('wechatUsers'));

        } catch (\Exception $e) {
            Log::error('微信用户查询失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return back()->with('error', '查询失败，请稍后重试');
        }
    }

    /**
     * 显示访问统计
     */
    public function statistics()
    {
        // 这里添加统计逻辑
        return view('wechat.users.statistics');
    }
} 